package com.xxx.controller;

import com.xxx.common.Code;
import com.xxx.common.Result;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/load")
public class LoadController {

    @Value("${file.uploadPath}")
    private String filePath;

    @RequiresRoles(value = {"admin","manage","employee"},logical = Logical.OR)
    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(filePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Result result = new Result(fileName,Code.SAVE_OK);
        return result;
    }

    @RequiresRoles(value = {"admin","manage","employee"},logical = Logical.OR)
    @GetMapping("/download")
    public void download(String name, HttpServletResponse resp){


        resp.setContentType("image/jpeg");
        try (
                FileInputStream fos = new FileInputStream(filePath + name);
                ServletOutputStream outputStream = resp.getOutputStream()
        ) {
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fos.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
